<?php

namespace App\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Cart extends Model
{
    protected $table = 'cart';
    protected $fillable = [
        'amount',
        'user_id',
        'product_sku_id',
        'product_id',
        'product_title',
        'product_image',
        'spec_sku_name'
    ];

    public $timestamps = false;

    protected $appends = ['total'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function productSku()
    {
        return $this->belongsTo(ProductSku::class);
    }

    public function product()
    {
        return $this->hasOneThrough(Product::class, ProductSku::class,'id','id','product_sku_id','product_id');
    }

    public function getTotalAttribute()
    {
        $productSku = $this->getAttribute('productSku');
        if($productSku)
        {
            return bcmul($this->amount, $productSku->price,2);
        }
        return 0;
    }

    public function getProductImageAttribute($value)
    {
        if($value && !Str::contains($value, config('upload.ossUrl')))
        {
            return  config('upload.ossUrl').$value;
        } elseif (Str::contains($value, config('upload.ossUrl'))) {
            return $value;
        } else {
            return  '';
        }
    }
}
